package com.weichen.delivery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weichen.delivery.common.R;
import com.weichen.delivery.dto.DishDto;
import com.weichen.delivery.dto.SetmealDto;
import com.weichen.delivery.entity.Category;
import com.weichen.delivery.entity.Dish;
import com.weichen.delivery.entity.Setmeal;
import com.weichen.delivery.entity.SetmealDish;
import com.weichen.delivery.service.CategoryService;
import com.weichen.delivery.service.DishService;
import com.weichen.delivery.service.SetmealDishService;
import com.weichen.delivery.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

//套餐管理
@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;
//    新增套餐
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

//    套餐信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
//        构造分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);//原先的页面
        Page<SetmealDto> setmealDtoPage = new Page<>();//copy后的页面，有套餐名称
//        条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper();
//        添加过滤条件
        queryWrapper.like(name != null,Setmeal::getName,name);
//        添加排序时间
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
//        执行分页查询
        setmealService.page(pageInfo,queryWrapper);
//        对象拷贝
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");//pageInfo中的属性records不进行拷贝，records是list整个页面的数据表单
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {//item为遍历的dish对象
            SetmealDto setmealDto = new SetmealDto();
//            当前setmealDto是自己创的，其他的属性都为空，所以要拷贝
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();//分类id
//            根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }


    /*
    @RequestParam：主要用于将请求参数区域的数据映射到控制层方法的参数上
    如果在请求中传入多个同名参数，比如：url?userName=zhl&userName=holley时怎么办？
    其实此时传入的数据格式是：“zhl,holley”,即多个数据之间使用逗号分隔开，在后台接口中可以使用数组或者list类型的变量来接收：
    public String requestparam8(@RequestParam(value="userName") String []  userNames)
    或者
    public String requestparam8(@RequestParam(value="list") List<String> list)
    @PathVariable绑定uri模板变量值：通过@PathVariable可以绑定占位符参数到方法参数中
     */
//    删除套餐
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){//@RequestParam用于
        setmealService.removeWithDish(ids);
        return R.success("套餐删除成功！");
    }

//    根据条件查询套餐数据
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }


//    点击图片查看套餐详情
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> showSetmealDish(@PathVariable Long id) {
        //条件构造器
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //手里的数据只有setmealId
        dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        //查询数据
        List<SetmealDish> records = setmealDishService.list(dishLambdaQueryWrapper);
        List<DishDto> dtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //copy数据
            BeanUtils.copyProperties(item,dishDto);
            //查询对应菜品id
            Long dishId = item.getDishId();
            //根据菜品id获取具体菜品数据，这里要自动装配 dishService
            Dish dish = dishService.getById(dishId);
            //其实主要数据是要那个图片，不过我们这里多copy一点也没事
            BeanUtils.copyProperties(dish,dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dtoList);
    }


//    套餐批量起售/停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable String status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Setmeal::getId, ids);
        updateWrapper.set(Setmeal::getStatus, status);
        setmealService.update(updateWrapper);
        return R.success("批量操作成功");
    }


//    套餐修改
//    数据回显
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        //拷贝数据
        BeanUtils.copyProperties(setmeal, setmealDto);
        //条件构造器
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        //根据setmealId查询具体的setmealDish
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        //然后再设置属性
        setmealDto.setSetmealDishes(setmealDishes);
        //作为结果返回
        return R.success(setmealDto);
    }


//    套餐修改
    @PutMapping
    public R<Setmeal> updateWithDish(@RequestBody SetmealDto setmealDto) {
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long setmealId = setmealDto.getId();
        //先根据id把setmealDish表中对应套餐的数据删了
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(queryWrapper);
        //然后在重新添加
        setmealDishes = setmealDishes.stream().map((item) ->{
            //这属性没有，需要我们手动设置一下
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        //更新套餐数据
        setmealService.updateById(setmealDto);
        //更新套餐对应菜品数据
        setmealDishService.saveBatch(setmealDishes);
        return R.success(setmealDto);
    }



}
